<template>
  <section class="set-box">
    <el-tabs v-model="activeName">
      <el-tab-pane label="基本信息设置" name="first">
        <div class="content">
          <div class="content-title">校园信息</div>
          <div class="content-text">
            <div class="name-box" style="position: relative;padding: 44px 0;"><span class="tatle">机构logo</span>
              <div class="imge " style="position: absolute; top: 0; left: 110px;"><img class="img-name" v-bind:src="schoolData.logo" /></div>
            </div>
            <div class="name-box"><span class="tatle">机构名称</span><span class="text">{{schoolData.name}}</span></div>
            <div class="name-box"><span class="tatle">机构地址</span><span class="text">{{schoolData.address}}</span></div>
          </div>
        </div>
        <div class="content">
          <div class="content-title">签约信息</div>
          <div class="content-text">
            <div class="name-box"><span class="tatle">开户人</span><span class="text">{{signInfo.bankOpenUser}}</span></div>
            <div class="name-box"><span class="tatle">开户银行</span><span class="text">{{signInfo.bank}}</span></div>
            <div class="name-box"><span class="tatle">银行卡号</span><span class="text">{{signInfo.corporateAccount}}</span></div>
            <div class="name-box"><span class="tatle">税率</span><span class="text">{{signInfo.rate * 100}}%</span></div>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="校园班级设置" name="second">
        <div class="grade">
          <el-button class=" float-r margin-b24" @click="operate(7)" type="primary">+ 添加班级</el-button>
          <div class="details" v-for='(item, j) in schoolClassList' :key="j">
            <div class="grade-title">
              <div class="titleName float-l">{{item.gradeYear}}级<span>({{item.classCount}}个班, 共{{item.studentTotal}}人)</span></div>
            </div>
            <div class="grade-box">
              <div v-for='(obj, index) in item.classList' :key='obj.id' class="grade-content" @mouseover='mouseover(obj.id)' @mouseout='mouseout(obj.id)' :class=" {'background-true': isIndex === obj.id} ">
                <span class="grade-name">{{obj.name}}</span>
                <span class="number">人数：{{obj.studentCount}}人</span>
                <span class="editor padding-l20" v-show='isIndex === obj.id' @click='operate(3, obj)'>编辑</span>
                <span class="editor padding-l15" v-show='isIndex === obj.id' @click='operate(6, obj, j, index)'>删除</span>
              </div>
            </div>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="管理员设置" name="thirdly" v-if="listRole('admin')">
        <el-button type="primary" size="small" class="float-r" @click="operate(8)">+ 添加管理员</el-button>
        <div class="grade">
          <ctable :thead="thead" :table-data="lists" :options="managerOptions" :page-data="pageObj" :serial="true" all-align="center"></ctable>
        </div>
      </el-tab-pane>
    </el-tabs>
    <el-dialog :visible.sync="dialogFormVisible" v-bind:close-on-click-modal='false' :before-close="handleClose" custom-class="modelClass">
      <span slot="title">添加班级</span>
      <el-form :model="parame" ref="parame" :rules="rules" label-width="100px" class="demo-ruleForm" label-position='left'>
        <el-form-item label="级别:" prop="gradeYear">
          <el-select v-model="parame.gradeYear" placeholder="请选择" style='width: 300px;' :disabled="showVal === 5">
            <el-option v-for="item in options" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="班级名称:" prop="name">
          <el-input type="text" v-model="parame.name" placeholder="请输入班级名称，长度不超过10个字" style='width: 300px;'></el-input>
        </el-form-item>
        <el-form-item label="毕业年份:" prop="graduateYear" >
          <el-select v-model="parame.graduateYear" placeholder="请选择" style='width: 300px;' :disabled="showVal === 5">
            <el-option v-for="item in graduateYearOptions" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button style='width: 100px;' type="primary" @click="submitForm('parame', showVal)">保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog
      title="提示"
      :visible.sync="dialogPass"
      size="tiny"
      @close="closePass">
      <el-form :model="passForm" :rules="rules" ref="passForm" label-width="100px">
        <el-form-item label="密码" prop="pass">
          <el-input type="password" v-model="passForm.pass" auto-complete="off" class="password"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPass">
          <el-input type="password" v-model="passForm.checkPass" auto-complete="off" class="password"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogPass = false">取 消</el-button>
        <el-button type="primary" @click="passwordConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </section>
</template>

<script>
import { schoolList, schoolClassGet, addSchool, schoolUpdate, schoolDel } from 'api/school/grade/index'
import { getRoleLists, setPassword } from 'api/common/index'
import ctable from 'components/common/ctable'
export default {
  data () {
    var nameCheck = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('班级名称不能为空'))
      } else {
        if (value.toString().length > 10 || value === Infinity) {
          return callback(new Error('输入班级名称，长度不超过10个字'))
        }
        callback()
      }
    }
    var gradeCheck = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请选择年级'))
      }
      callback()
    }
    var graduateYearCheck = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请选择日期'))
      }
      callback()
    }
    let validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.passForm.checkPass !== '') {
          this.$refs.passForm.validateField('checkPass')
        }
        callback()
      }
    }
    let validatePassCheck = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.passForm.pass) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      rules: {
        gradeYear: [
           { validator: gradeCheck, trigger: 'blur' }
        ],
        name: [
           { validator: nameCheck, trigger: 'blur' }
        ],
        graduateYear: [
          { validator: graduateYearCheck, trigger: 'blur' }
        ],
        pass: [
          { validator: validatePass, trigger: 'change' }
        ],
        checkPass: [
          { validator: validatePassCheck, trigger: 'blur' }
        ]
      },
      isIndex: '', // 显示隐藏编辑和保存按钮
      showVal: 4, // 区分添加还是编辑（4添加， 5编辑）
      schoolData: {}, // 学校详情
      signInfo: {}, // 签约信息
      schoolClassList: [], // 班级列表
      activeName: 'first', // 显示那个tab
      dialogFormVisible: false, // 是否显示模态框
      options: [], // 年级列表
      graduateYearOptions: [], // 毕业年份列表
      parame: {},  // 添加编辑年级参数
      userId: 0, // 用户id
      passForm: {
        pass: '',
        checkPass: ''
      }, // 修改密码
      dialogPass: false, // 修改密码弹窗显示
      lists: [], // 数据列表
      thead: [{ // ctable组件头
        name: '角色',
        prop: 'remark'
      }, {
        name: '登陆账号',
        prop: 'mobile'
      }, {
        name: '账号权限',
        prop: 'nets',
        format: this.hanleRole
      }],
      managerOptions: [{
        name: '编辑',
        callback: this.goEditManager
      }, {
        name: '修改密码',
        callback: this.changePassword
      }],
      pageObj: { // 分页
        page: {},
        callback: this.getData
      }
    }
  },
  created () {
    if (this.$store.getters.getSystemInfo) { // 在不刷新本页情况下防止多次请求
      ({ net: this.schoolData, settings: this.signInfo } = this.$store.getters.getSystemInfo)
    } else {
      this.$store.dispatch('setSystemInfo').then(data => {
        ({ net: this.schoolData, settings: this.signInfo } = data)
      })
    }
    this.operate(1) // 年级下拉框列表
    this.operate(2) // 班级列表
    if (this.$store.getters.getRole === 0) {
      getRoleLists().then(res => {
        this.lists = res.data
      })
    }
  },
  methods: {
    hanleRole (row, col, val) {
      let str = ''
      val[0].netMenu.forEach(item => {
        str += `${item.name}|`
      })
      return str.substr(0, str.length - 1)
    },
    submitForm (formName, val) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.operate(val)
        }
      })
    },
    operate (val, obj, j, index) {
      switch (parseInt(val)) {
        case 1: // 年级下拉框列表
          let nowYear = new Date().getFullYear()
          for (let i = 3; i >= 0; i--) {
            this.options.push(nowYear + i)
          }
          for (let i = 1; i <= 9; i++) {
            this.options.push(nowYear - i)
          }
          let num = this.options[0]
          for (let i = 6; i >= 1; i--) {
            this.graduateYearOptions.push(num + i)
          }
          this.graduateYearOptions = [...this.graduateYearOptions, ...this.options]
          break
        case 2: // 班级列表
          schoolList().then(res => {
            this.schoolClassList = res.data
          })
          break
        case 3: // 班级详情
          this.showVal = 5
          this.dialogFormVisible = true
          schoolClassGet({id: obj.id}).then(res => {
            this.parame = {
              id: res.data.id,
              name: res.data.name,
              gradeYear: res.data.gradeYear.toString(),
              graduateYear: res.data.graduateYear
            }
          })
          break
        case 4: // 添加班级
          let graduateYear = Number(this.parame.graduateYear)
          let gradeYear = Number(this.parame.gradeYear)
          if (graduateYear <= gradeYear) {
            return this.$alert('毕业年份必须大于级别年份', '提示', {
              confirmButtonText: '确定',
              callback: function () {}
            })
          }
          addSchool({name: this.parame.name, gradeYear: gradeYear, graduateYear: graduateYear}).then(res => {
            this.$message({
              type: 'success',
              message: '添加成功!'
            })
            this.operate(2)
            this.dialogFormVisible = false
          })
          break
        case 5: // 编辑班级
          this.dialogFormVisible = false
          schoolUpdate({id: this.parame.id, name: this.parame.name, gradeYear: Number(this.parame.gradeYear), graduateYear: Number(this.parame.graduateYear)}).then(res => {
            this.$message({
              type: 'success',
              message: '编辑成功!'
            })
            this.operate(2)
          })
          break
        case 6: // 删除班级
          if (obj.studentCount) {
            return this.$alert('请将班级里的学生清空后，再进行删除', '提示', {
              confirmButtonText: '确定',
              type: 'warning'
            })
          }
          this.$confirm('班级删除后，不可再查询该班级的缴费记录信息，是否确认删除？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.schoolClassList[j].classList.splice(index, 1)
            schoolDel({id: obj.id}).then(res => {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              this.operate(2) // 班级列表
            })
          })
          break
        case 7:
          this.parame = {
            id: '',
            name: '',
            gradeYear: ''
          }
          this.showVal = 4
          this.dialogFormVisible = true
          break
        case 8: // 添加管理员
          if (this.lists.length >= 5) return this.$message({type: 'warning', message: '管理员最多只能添加5个'})
          let account = JSON.parse(window.localStorage.loginForm).username
          let allList = [`${account}01`, `${account}02`, `${account}03`, `${account}04`, `${account}05`]
          let addAcc = []
          let isExist = false
          allList.some(item => {
            isExist = false
            this.lists.some(obj => {
              if (item === obj.mobile) {
                isExist = true
                return true
              }
            })
            if (!isExist) addAcc.push(item)
          })
          this.$router.push({name: 'addManager', query: {account: addAcc[0]}})
          break
      }
    },
    changePassword (obj) { // 修改密码
      this.userId = obj.id
      this.dialogPass = true
    },
    passwordConfirm () { // 密码确认
      this.$refs.passForm.validate(async valid => {
        if (valid) {
          await setPassword({id: this.userId, password: this.passForm.pass})
          this.dialogPass = false
          this.$message({
            message: '修改成功',
            type: 'success'
          })
        }
      })
    },
    closePass (done) { // 关闭密码修改回调
      this.$refs.passForm.resetFields()
    },
    mouseover (index) {
      this.isIndex = index
    },
    mouseout (index) {
      this.isIndex = ''
    },
    handleClose () {
      this.dialogFormVisible = false
    },
    goEditManager (obj) {
      this.$router.push({name: 'editManager', query: {id: obj.id}})
    }
  },
  components: {
    ctable
  }
}
</script>
<style lang="less">
.set-box{height: 100%; overflow-y: auto;padding: 10px 25px;}
.set-box .content{border: 1px solid #d3dce6; border-radius: 10px;margin-top: 20px;}
.set-box .content .content-title{border-bottom: 1px solid #d3dce6; padding: 10px;color: #323232;}
.set-box .content .content-text{padding: 14px 10px;}
.set-box .content .content-text .name-box{padding: 12px 0; clear: both;}
.set-box .content .content-text .imge{width: 100px;height: 100px; border: 1px solid #d3dce6;}
.set-box .content .content-text .img-name{ width: 100%; height: 100%;}
.set-box .content .content-text .text{padding-left: 20px;color: #666666;}
.set-box .content .content-text .tatle{width: 90px;display: inline-block;color: #999999;}
.set-box .grade{padding: 20px 0;}
.set-box .grade .details{clear: both;border: 1px solid #e1e1e1; border-radius: 10px;margin-bottom: 20px;}
.set-box .grade .details .grade-title{border-bottom: 1px solid #e1e1e1; clear: both;height: 40px; line-height: 40px; margin: 0 14px;}
.set-box .grade .details .titleName{color: #333333;}
.set-box .grade .details .titleName span{color: #666666;}
.set-box .grade .details .editor{ color: #437fd7;cursor: pointer; }
.set-box .grade .grade-box{padding: 20px 0;}
.set-box .grade .grade-content{padding: 10px 14px;}
.set-box .grade .grade-content .grade-name{color: #666666;  width: 150px; display: inline-block;}
.set-box .grade .grade-content .number{ width: 150px; display: inline-block; padding-right: 60px;color: #7f7f7f;}
.set-box .model {clear: both;padding-bottom: 25px;}
.set-box .model .title{width: 100px;  line-height: 34px; padding-left: 24px;}
.set-box .model .prompt{color: red; line-height: 34px; padding-left: 12px;}
.set-box .model .inputNAme{width: 300px; height: 36px; border: 1px solid #bfcbd9; border-radius: 4px;}
.set-box .model .inputNAme::placeholder {color: #97a8be}
.set-box .model .inputNAme:hover { border-color: #8391a5}
.set-box .model .inputNAme:focus { outline: none; border-color: #20a0ff;}
.set-box .dialog-footer{text-align: center;}
.set-box .dialog-footer .bottom{width: 120px;}
.set-box .float-r{float: right;}
.set-box .float-l{float: left;}
.set-box .margin-b24{ margin-bottom: 24px;}
.set-box .width-300{width: 300px;}
.set-box .padding-t30{padding-top: 30px;}
.set-box .padding-l20{padding-left: 20px;}
.set-box .padding-l15{padding-left: 15px;}
.set-box .background-true{background: #f6f6f6;}
.set-box .modelClass {width: 500px;}
.set-box .modelClass .el-dialog__header{background-color: #457ed8;padding-bottom: 16px;color: #ffffff;}
.set-box .modelClass .el-dialog__headerbtn .el-dialog__close{color: #ffffff;}
.set-box .password {
  width: 200px;
}
</style>
